package com.example.mes_common.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Jackson JSON工具类
 */
@Slf4j
public class JacksonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        // 初始化配置
        OBJECT_MAPPER
                // 设置时区
                .setTimeZone(TimeZone.getTimeZone("GMT+8"))
                // 设置日期格式
                .setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                // 忽略未知属性
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                // 忽略空Bean转json的错误
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                // 非空才序列化
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                // 注册Java8时间模块
                .registerModule(new JavaTimeModule())
                // 美化输出（仅开发环境使用）
                .configure(SerializationFeature.INDENT_OUTPUT, false);
    }

    /**
     * 对象转JSON字符串
     */
    public static String toJson(Object obj) {
        if (obj == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转JSON出错: {}", e.getMessage(), e);
            throw new RuntimeException("对象转JSON出错", e);
        }
    }

    /**
     * JSON字符串转对象
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (!StringUtils.hasText(json) || clazz == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, clazz);
        } catch (IOException e) {
            log.error("JSON转对象出错: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转对象出错", e);
        }
    }

    /**
     * JSON字符串转复杂对象（如List、Map等）
     */
    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (!StringUtils.hasText(json) || typeReference == null) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("JSON转复杂对象出错: {}", e.getMessage(), e);
            throw new RuntimeException("JSON转复杂对象出错", e);
        }
    }

    /**
     * JSON字符串转JsonNode
     */
    public static JsonNode readTree(String json) {
        if (!StringUtils.hasText(json)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readTree(json);
        } catch (IOException e) {
            log.error("JSON解析出错: {}", e.getMessage(), e);
            throw new RuntimeException("JSON解析出错", e);
        }
    }

    /**
     * 对象深度拷贝
     */
    public static <T> T deepCopy(T obj, Class<T> clazz) {
        return fromJson(toJson(obj), clazz);
    }

    /**
     * 格式化JSON字符串（美化输出）
     */
    public static String formatJson(String json) {
        try {
            Object jsonObject = OBJECT_MAPPER.readValue(json, Object.class);
            return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
        } catch (IOException e) {
            log.error("JSON格式化出错: {}", e.getMessage(), e);
            return json;
        }
    }
}
